package com.xqboss.apps.controller.system;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.github.pagehelper.PageHelper;
import com.xqboss.apps.domain.consumer.ConsumerAnnouncementMsg;
import com.xqboss.apps.domain.consumer.ConsumerHistoryActivity;
import com.xqboss.apps.domain.consumer.ConsumerInteractMsg;
import com.xqboss.apps.domain.sys.SysAnnouncementMsg;
import com.xqboss.apps.dto.PageDto;
import com.xqboss.apps.dto.system.SysAnnouncementMsgDto;
import com.xqboss.apps.service.consumer.ConsumerAnnouncementMsgService;
import com.xqboss.apps.service.consumer.ConsumerHistoryActivityService;
import com.xqboss.apps.service.consumer.ConsumerInteractMsgService;
import com.xqboss.apps.service.sys.SysAnnouncementCategoryService;
import com.xqboss.apps.service.sys.SysAnnouncementMsgService;
import com.xqboss.apps.service.sys.SysHistoryActivityService;
import com.xqboss.apps.vo.sys.SysAnnouncementCategoryVo;
import com.xqboss.apps.vo.sys.SysAnnouncementMsgVo;
import com.xqboss.apps.vo.sys.SysHistoryActivityVo;
import com.xqboss.common.annotation.RepeatSubmit;
import com.xqboss.common.core.controller.BaseController;
import com.xqboss.common.core.domain.R;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.NotNull;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 公告消息表接口
 *
 * @author wangcong
 * @date 2023-08-31
 */
@Api(tags = "公告消息管理")
@RestController
@RequestMapping("/apps/announcement")
public class SysAnnouncementMsgController extends BaseController {

    @Autowired
    private SysAnnouncementMsgService sysAnnouncementMsgService;
    @Autowired
    private ConsumerAnnouncementMsgService consumerAnnouncementMsgService;
    @Autowired
    private SysHistoryActivityService sysHistoryActivityService;
    @Autowired
    private ConsumerInteractMsgService consumerInteractMsgService;
    @Autowired
    private ConsumerHistoryActivityService consumerHistoryActivityService;
    @Autowired
    private SysAnnouncementCategoryService sysAnnouncementCategoryService;

    @ApiOperation("公告消息详情")
    @GetMapping("info/{id}")
    public R<SysAnnouncementMsgVo> findByKey(@PathVariable("id")
                                             @ApiParam(value = "公告消息ID", required = true)
                                             @NotNull(message = "ID不能为空")
                                             Long id) {
        SysAnnouncementMsg msg = sysAnnouncementMsgService.getById(id);
        SysAnnouncementMsgVo vo = BeanUtil.copyProperties(msg, SysAnnouncementMsgVo.class);
        return R.ok(vo);
    }

    @RepeatSubmit(interval = 1000, justUrl = true)
    @ApiOperation("编辑公告消息")
    @PutMapping("update")
    public R update(@RequestBody SysAnnouncementMsgDto dto) {
        SysAnnouncementMsg sysMsg = sysAnnouncementMsgService.getById(dto.getId());
        Objects.requireNonNull(sysMsg, "资源不存在");
        if (ObjUtil.equal(dto.getIsRead(), 1)) {
            LambdaQueryWrapper<ConsumerAnnouncementMsg> wq = new LambdaQueryWrapper<>();
            wq.eq(ConsumerAnnouncementMsg::getAnnouncementId, sysMsg.getId());
            wq.eq(ConsumerAnnouncementMsg::getUserId, getUserId());
            wq.last("limit 1");
            ConsumerAnnouncementMsg one = consumerAnnouncementMsgService.getOne(wq);
            if (ObjUtil.isNotNull(one)) {
                return R.ok();
            }

            ConsumerAnnouncementMsg msg = new ConsumerAnnouncementMsg();
            msg.setAnnouncementId(sysMsg.getId());
            msg.setUserId(getUserId());
            consumerAnnouncementMsgService.save(msg);
        }
        return R.ok();
    }

    @ApiOperation("公告分类数据")
    @GetMapping("data")
    public R<List<SysAnnouncementCategoryVo>> categoryData() {
        List<SysAnnouncementCategoryVo> categories = sysAnnouncementCategoryService.categoryData(getUserId());
        return R.ok(categories);
    }

    @ApiOperation("公告列表")
    @PostMapping("list")
    public R<List<SysAnnouncementMsgVo>> findBy(@RequestBody SysAnnouncementMsgDto dto) {
        dto.setUserId(getUserId());
        PageHelper.startPage(dto.getPageNum(), dto.getPageSize()).setReasonable(true);
        List<SysAnnouncementMsgVo> list = sysAnnouncementMsgService.findByList(dto);
        return R.ok(list);
    }

    @ApiOperation("历史活动列表")
    @PostMapping("history-list")
    public R<List<SysHistoryActivityVo>> historyList(@RequestBody PageDto dto) {
        Long userId = getUserId();
        dto.startPage();
        List<SysHistoryActivityVo> list = sysHistoryActivityService.historyList(userId);
        //点击一次自动已读所有消息
        if (CollUtil.isNotEmpty(list)) {
            List<Long> sysIds = list.stream().map(SysHistoryActivityVo::getId).collect(Collectors.toList());

            List<ConsumerHistoryActivity> consumerList = consumerHistoryActivityService.list(new LambdaQueryWrapper<ConsumerHistoryActivity>()
                    .select(ConsumerHistoryActivity::getActivityId)
                    .eq(ConsumerHistoryActivity::getUserId, userId)
                    .in(ConsumerHistoryActivity::getActivityId, sysIds));
            if (CollUtil.isNotEmpty(consumerList)) {
                List<Long> conList = consumerList.stream().map(ConsumerHistoryActivity::getActivityId).collect(Collectors.toList());
                sysIds.removeIf(conList::contains);
            }

            if (CollUtil.isNotEmpty(sysIds)) {
                ArrayList<ConsumerHistoryActivity> res = new ArrayList<>();
                sysIds.forEach(item -> {
                    ConsumerHistoryActivity activity = new ConsumerHistoryActivity();
                    activity.setActivityId(item);
                    activity.setUserId(userId);
                    res.add(activity);
                });
                consumerHistoryActivityService.saveBatch(res);
            }
        }
        return R.ok(list);
    }

    @ApiOperation("已读所有公告")
    @PutMapping("/readAll")
    public R readAll(@RequestBody SysAnnouncementMsgDto dto) {
        Long userId = getUserId();
        //已读所有互动消息
        consumerInteractMsgService.update(new LambdaUpdateWrapper<ConsumerInteractMsg>()
                .set(ConsumerInteractMsg::getStatus, 1)
                .eq(ConsumerInteractMsg::getUserId, userId));

        //已读所有公告消息
        List<SysAnnouncementMsg> sysList = sysAnnouncementMsgService.list();
        if (CollUtil.isEmpty(sysList)) {
            return R.ok_msg( "已清除全部消息");
        }
        List<Long> sysIds = sysList.stream().map(SysAnnouncementMsg::getId).collect(Collectors.toList());
        LambdaQueryWrapper<ConsumerAnnouncementMsg> wq = new LambdaQueryWrapper<>();
        wq.eq(ConsumerAnnouncementMsg::getUserId, userId);
        wq.in(ConsumerAnnouncementMsg::getAnnouncementId, sysIds);
        List<ConsumerAnnouncementMsg> consumerList = consumerAnnouncementMsgService.list(wq);
        if (CollUtil.isNotEmpty(consumerList)) {
            List<Long> conList = consumerList.stream().map(ConsumerAnnouncementMsg::getAnnouncementId).collect(Collectors.toList());
            sysIds.removeIf(conList::contains);
        }
        if (CollUtil.isNotEmpty(sysIds)) {
            ArrayList<ConsumerAnnouncementMsg> res = new ArrayList<>();
            sysIds.forEach(item -> {
                ConsumerAnnouncementMsg msg = new ConsumerAnnouncementMsg();
                msg.setAnnouncementId(item);
                msg.setUserId(userId);
                res.add(msg);
            });
            consumerAnnouncementMsgService.saveBatch(res);
        }
        return R.ok_msg( "已清除全部消息");
    }
}
